package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuHasStockTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.to.order.OrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.exception.NoStockException;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.omg.SendingContext.RunTime;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    OrderFeignService orderFeignService;


    /**
     * 解锁库存
     *
     * @param skuId
     * @param wareId
     * @param num
     * @param detailId
     */
    private void unlockStock(Long skuId, Long wareId, Integer num, Long detailId) {
        //库存解锁
        wareSkuDao.unlockStock(skuId, wareId, num);
        //库存工作单改为解锁状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(detailId);
        detailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(detailEntity);
    }

    @Override
    public List<SkuHasStockTo> getHasStock(List<Long> skuIds) {
        List<SkuHasStockTo> collect = skuIds.stream().map((id) -> {
            SkuHasStockTo stockTo = new SkuHasStockTo();
            //查询当前sku的总库存量
            Long count = this.baseMapper.getSkuStock(id);
            stockTo.setSkuId(id);
            stockTo.setHasStock(count == null ? false : count > 0);
            return stockTo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁库存
     *
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) throws NoStockException {
        /**
         * 保存工作单的详情
         * 以便于追溯
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());//保存订单号
        wareOrderTaskService.save(taskEntity);

        //1.按照下单的收获地址，选择一个就近仓库，锁定库存（暂时不做）
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(lock -> {
            Long skuId = lock.getSkuId();
            SkuWareHasStock stock = new SkuWareHasStock();
            stock.setSkuId(skuId);
            //1.1查询当前skuId 所在的仓库库存
            List<Long> wareId = wareSkuDao.listWareHasStock(skuId);
            stock.setWareId(wareId);
            stock.setNum(lock.getCount());
            return stock;
        }).collect(Collectors.toList());

        //2. 锁定库存
        for (SkuWareHasStock stock : collect) {
            Boolean skuStock = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();

            if (wareIds == null || wareIds.size() == 0) {
                //没有仓库有库存
                throw new NoStockException(skuId);
            } else {
                for (Long wareId : wareIds) {
                    //扣库存  0 为失败
                    Long result = wareSkuDao.lockStock(skuId, wareId, stock.getNum());
                    if (result == 0) {
                        //当前仓库失败 ，继续下一个
                    } else {
                        //当前仓库成功
                        //TODO 库存锁定成功
                        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null, skuId, null, stock.getNum(), taskEntity.getId(), wareId, 1);
                        //保存详情订单
                        wareOrderTaskDetailService.save(detailEntity);
                        StockLockedTo lockedTo = new StockLockedTo();
                        lockedTo.setId(taskEntity.getId());
                        StockDetailTo stockDetailTo = new StockDetailTo();
                        BeanUtils.copyProperties(detailEntity, stockDetailTo);

                        lockedTo.setStockDetail(stockDetailTo);

                        log.info("正在发送消息给 stock-event-exchange ");
                        rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo);
                        skuStock = true;
                        break;
                    }
                }
            }
            if (skuStock == false) {
                //所有仓库都没库存
                throw new NoStockException(skuId);
            }
        }
        //全部成功

        return true;
    }

    /**
     * 监听者 收取消息执行的方法
     *
     * @param to
     */
    @Override
    public void unlockStock(StockLockedTo to) {

        StockDetailTo stockDetail = to.getStockDetail();
        Long skuId = stockDetail.getSkuId();
        Long detailId = stockDetail.getId();

        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);


        if (byId != null) {
            Long toId = to.getId();

            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(toId);
            String orderSn = taskEntity.getOrderSn();

            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
                });
                System.out.println("orderVo.getStatus() =="+orderVo.getStatus());
                if (orderVo == null || orderVo.getStatus() == 4) {
                    if(byId.getLockStatus()==1){
                        //订单被取消了，解锁库存
                        unlockStock(skuId, stockDetail.getWareId(), stockDetail.getSkuNum(), detailId);
                    }
                }
            } else {
                throw new RuntimeException("远程服务解锁失败");
            }
        } else {
            //无需解锁

        }
    }

    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新的库存解锁状态,防止重复解锁
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        //根据taskId找到所有未解锁的工作单
        List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", task.getId()).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : entities) {
            unlockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
    }

    @Data
    private class SkuWareHasStock {
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId) && Integer.parseInt(skuId) != 0) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId) && Integer.parseInt(wareId) != 0) {
            wrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //如果还没有库存记录，新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        System.out.println("在addStock内--" + "skuId" + skuId + "wareId:" + wareId + "skuNum:" + skuNum);
        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            try {
                //查询远程的sku的名字
                R r = productFeignService.info(skuId);
                if (r.getCode() == 0) {
                    Map<String, Object> skuInfo = (Map<String, Object>) r.get("skuInfo");
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            wareSkuDao.insert(wareSkuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }


    }

}